<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="组织机构" prop="orgId">
                <el-tree-select v-model="queryParams.orgId" :data="options.orgOptions" check-strictly
                    :props="{ value: 'id', label: 'name', children: 'children' }" placeholder="请选择组织机构" clearable
                    style="width: 200px" />
            </el-form-item>
            <el-form-item label="岗位" prop="postKey">
                <el-input v-model="queryParams.postKey" placeholder="请输入岗位编码/名称" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="danger" v-hasFunc="'poststaff:del'" plain icon="delete" :disabled="multiple"
                    @click="handleDelete">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" v-hasFunc="'poststaff:add'" plain icon="plus"
                    @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" v-hasFunc="'poststaff:edit'" plain icon="edit" :disabled="single"
                    @click="handleUpdate">修改</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" ref="tableRef" row-key="id" :data="dataList"
            @selection-change="handleSelectionChange" @row-click="handleRowClick" highlight-current-row>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="系统编码" align="center" prop="id" :show-overflow-tooltip="true"
                v-if="columns.showColumn('id')">
                <template #default="scope">
                    {{ scope.row.id }}
                </template>
            </el-table-column>
            <el-table-column label="组织机构" align="center" prop="orgId" :show-overflow-tooltip="true"
                v-if="columns.showColumn('orgId')">
                <template #default="scope">
                    {{ scope.row.org.name }}
                </template>
            </el-table-column>
            <el-table-column label="岗位" align="center" prop="postId" :show-overflow-tooltip="true"
                v-if="columns.showColumn('postId')">
                <template #default="scope">
                    {{ scope.row.post.name }}
                </template>
            </el-table-column>
            <el-table-column label="编制人数" align="center" prop="staffingNum" :show-overflow-tooltip="true"
                v-if="columns.showColumn('staffingNum')">
                <template #default="scope">
                    {{ scope.row.staffingNum }}
                </template>
            </el-table-column>
            <el-table-column label="在岗人数" align="center" prop="actualNum" :show-overflow-tooltip="true"
                v-if="columns.showColumn('actualNum')">
                <template #default="scope">
                    {{ scope.row.actualNum }}
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"
                v-if="columns.showColumn('remark')">
                <template #default="scope">
                    {{ scope.row.remark }}
                </template>
            </el-table-column>
            <el-table-column label="启用状态" align="center" prop="isActive" :show-overflow-tooltip="true"
                v-if="columns.showColumn('isActive')">
                <template #default="{ row }">
                    <dict-tag :options="sys_normal_disable" :value="row.isActive" />
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="primary" v-hasFunc="'poststaff:del'" text icon="delete"
                        @click="handleDelete(scope.row)">删除</el-button>
                    <el-button type="primary" v-hasFunc="'poststaff:edit'" text icon="edit"
                        @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button type="primary" text icon="view" @click="handleView(scope.row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body draggable align-center
            :close-on-click-modal="false" destroy-on-close>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-row :gutter="20">
                    <el-col :lg="24">
                        <el-form-item label="系统编码" prop="id">
                            <el-input v-model="form.id" placeholder="保存后自动生成" clearable disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="组织机构" prop="orgId">
                            <el-tree-select v-model="form.orgId" :data="options.orgOptions" check-strictly
                                :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id"
                                :render-after-expand="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="岗位" prop="postId">
                            <el-select v-model="form.postId" placeholder="请选择岗位" clearable filterable>
                                <el-option v-for="item in options.postOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="编制人数" prop="staffingNum">
                            <el-input-number v-model="form.staffingNum" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12" v-show="false">
                        <el-form-item label="在岗人数" prop="actualNum">
                            <el-input-number v-model="form.actualNum" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="状态" prop="isActive">
                            <el-radio-group v-model="form.isActive">
                                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{
                                    dict.label
                                }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" :rows="4" resize="none" v-model="form.remark"
                                placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="submitForm" v-if="operateType == 0 || operateType == 1">确
                    定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { listOrgPost, getOrgPost, delOrgPost, addOrgPost, updateOrgPost } from "@/api/system/orgpost.js";
import { listPost } from "@/api/system/post";
import { treeDeptList } from "@/api/system/dept";
const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

//弹窗操作类型
//0:新增，1：修改，2:查看
const operateType = ref(0)
//表单ref
const formRef = ref();
const tableRef = ref();
// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);




//默认时间范围
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    orgId: undefined,
    postKey: undefined,
});


const state = reactive({
    single: true,
    multiple: true,
    form: {
        id: undefined,
        orgId: undefined,
        postId: undefined,
        staffingNum: 0,
        actualNum: 0,
        remark: undefined,
        isActive: true
    },
    rules: {
        orgId: [
            { required: true, message: "请选择组织机构", trigger: "change" }
        ],
        postId: [
            { required: true, message: "请选择岗位", trigger: "change" }
        ],
    },
    options: {
        //组织机构
        orgOptions: [],
        postOptions: [],
    }
})

const { form, rules, options, single, multiple } = toRefs(state)


//所有列
const columns = ref([
    { visible: false, prop: 'id', label: '系统编码' },
    { visible: true, prop: 'orgId', label: '组织机构' },
    { visible: true, prop: 'postId', label: '岗位' },
    { visible: true, prop: 'staffingNum', label: '编制人数' },
    { visible: true, prop: 'actualNum', label: '在岗人数' },
    { visible: false, prop: 'remark', label: '备注' },
    { visible: true, prop: 'isActive', label: '状态' },
]);

// 获取列表方法
const getList = () => {
    loading.value = true;
    listOrgPost(queryParams).then((response) => {
        dataList.value = response.result;
        total.value = response.totalNum;
        loading.value = false;
    });
};

// 重置表单
const reset = () => {
    form.value = {
        id: undefined,
        orgId: undefined,
        postId: undefined,
        staffingNum: 0,
        actualNum: 0,
        remark: undefined,
        isActive: true
    };
    proxy.resetForm("form");
};

// 搜索按钮操作
const handleQuery = () => {
    queryParams.pageNum = 1;
    getList();
};

// 重置按钮操作
const resetQuery = () => {
    reset();
    handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
    selected.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
    reset();
    operateType.value = 0;
    open.value = true;
    title.value = "添加数据";
};

// 修改按钮操作
const handleUpdate = (row) => {
    reset();
    operateType.value = 1;
    const key = row.id || selected.value;
    getOrgPost(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "修改数据";
    });
};

// 行点击事件
const handleRowClick = (row) => {
    tableRef.value.toggleRowSelection(row);
};


//查看
const handleView = (row) => {
    reset();
    operateType.value = 2;
    var key = row.id;
    getOrgPost(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "查看明细";
    });
}

// 提交按钮
const submitForm = () => {
    const validateForm = formRef.value?.validate;
    if (validateForm) {
        validateForm((valid) => {
            if (valid) {
                const apiCall = form.value.id ? updateOrgPost : addOrgPost;
                apiCall(form.value).then(() => {
                    proxy.$modal.msgSuccess("操作成功");
                    open.value = false;
                    getList();
                });
            }
        });
    }
};

//取消弹窗
const cancel = () => {
    open.value = false;
    proxy.resetForm("form")
}

// 删除按钮操作
const handleDelete = (row) => {
    const keys = [].concat(row.id || selected.value);
    proxy.$modal.confirm("是否确认删除编号为" + keys + "的数据项？")
        .then(() => delOrgPost(keys))
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
};

const getPostList = () => {
    return listPost({ pageSize: 9999 }).then(res => {
        options.value.postOptions = res.result.map(item => ({
            value: item.id,
            label: item.name
        }));
    });
}


const getOrgTree = () => {
    let treeParams = { includeSelf: false };
    treeDeptList(treeParams).then(response => {
        options.value.orgOptions = response;
    });
}

// 页面加载时调用获取列表方法
onMounted(() => {
    getList();
    getPostList();
    getOrgTree();
});
</script>
